package com.pascal91.webpp.controller;

import com.pascal91.webpp.model.Message;
import com.pascal91.webpp.model.Users;
import com.pascal91.webpp.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Controller
public class MessageController {

    @Autowired
    MessageService messageService;

    @RequestMapping("/chat.html")
    public ModelAndView chat(Model model) {
        model.addAttribute("message", new Message());
        model.addAttribute("messagesList", messageService.getMessagesList());
        return new ModelAndView("chat");
    }

    @RequestMapping(value = "/addMessage/", method = RequestMethod.POST)
        public ModelAndView login(HttpSession httpSession, Model model, Message message){

            ModelAndView view = new ModelAndView("redirect:/chat.html");
            Users user = (Users) httpSession.getAttribute("user");

            if(user != null){
                message.setUser(user);
                message.setTimeStamp(new Date());
                messageService.addMessage(message);
            }

            return view;
    }

}
